﻿using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace redis_microservice.Controllers
{
    /// <summary>
    /// 有序项唯一集合 -> 常用于当作排行榜使用
    /// </summary>
    public class ZSetController(IConnectionMultiplexer connection) : BaseController(connection)
    {
        /// <summary>
        /// 获取所有项
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> Get(string key = "user:order:leaderboard")
        {
            // 按分值从大到小降序排列(如果分值相同, 则先加入的更大一些)
            var zset = await _db0.SortedSetRangeByScoreAsync(key, order:Order.Descending);
            return Ok(zset.Select(x => new { Item = x.ToString() }));
        }

        /// <summary>
        /// 新增一项
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Set
            (string key = "user:order:leaderboard", string val = "666", double score = 100)
        {
            bool res = await _db0.SortedSetAddAsync(key, val, score); // 返回 false 表示值已存在且已更新分值
            return Ok(res);
        }

        /// <summary>
        /// 删除一项
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Del(string key = "user:order:leaderboard", string val = "666")
        {
            bool res = await _db0.SortedSetRemoveAsync(key, val); // 返回 false 表示值不存在
            return Ok(res);
        }
    }
}
